package cn.lg.soar.message.client;

import cn.lg.soar.core.annotations.ApiClient;
import cn.lg.soar.core.config.cache.template.ICacheTemplate;
import cn.lg.soar.message.api.constant.ModuleConst;
import cn.lg.soar.message.api.model.MailDTO;
import cn.lg.soar.message.api.service.IMailApi;
import cn.lg.soar.message.service.IMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.time.Duration;
import java.util.Objects;

/**
 * @author luguoxiang
 * @date 2022/1/3
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@ApiIgnore
@ApiClient("boot")
@RestController
@RequestMapping(ModuleConst.CLIENT_PATH + "/mail")
public class MailApiClient implements IMailApi {

    @Autowired
    private IMailService service;
    @Autowired
    private ICacheTemplate<String, Object> cacheTemplate;

    private final String CAPTCHA_KEY = "captcha:email:";

    @PostMapping("send")
    @Override
    public void send(@RequestBody MailDTO mail) {
        service.send(mail.getTo(), mail.getSubject(), mail.getContent());
    }

    @PostMapping("sendCaptcha")
    @Override
    public void sendCaptcha(String email, String subject, Duration expire, String captcha) {
        String key = CAPTCHA_KEY + email;
        if (cacheTemplate.get(key) != null) {
            // 禁止频繁发送邮件影响客户体验
            cacheTemplate.expire(key, expire);
            return;
        }
        cacheTemplate.put(CAPTCHA_KEY + email, captcha, expire);
        service.send(email, subject, captcha);// TODO 设置验证码内容模板（数据库配置模板方式）
    }

    @GetMapping("checkCaptcha")
    @Override
    public boolean checkCaptcha(String email, String captcha, Boolean delete) {
        email = CAPTCHA_KEY + email;
        Object o = cacheTemplate.get(email);
        if (!Boolean.FALSE.equals(delete)) {
            cacheTemplate.delete(email);
        }
        return Objects.equals(captcha, o);
    }

}
